package com.pansoft.openplanet.fragment;

import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.efounder.chat.http.JFCommonRequestManager;
import com.efounder.common.BaseRequestManager;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.recycleviewhelper.CommonAdapter;
import com.efounder.utils.ResStringUtil;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.activity.TradeLineActivity;
import com.pansoft.openplanet.activity.TransactionDetailActivity;
import com.pansoft.openplanet.bean.TransactionBean;
import com.pansoft.openplanet.constant.IPAssetsConstant;
import com.pansoft.openplanet.util.BtcNetParamUtil;
import com.pansoft.openplanet.util.EosNetParamUtil;
import com.pansoft.openplanet.util.TCRequestUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.utilcode.util.TimeUtils;
import com.utilcode.util.ToastUtils;

import org.bitcoinj.core.Coin;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.pansoft.openplanet.activity.TradeLineActivity.TRANSACTION_TYPE_IN;
import static com.pansoft.openplanet.activity.TradeLineActivity.TRANSACTION_TYPE_OUT;

/**
 * 交易记录列表
 */
public class TransactionListFragment extends BaseFragment {

    public static final String TAG = "TransactionListFragment";
    private RecyclerView recyclerView;
    private SmartRefreshLayout refreshLayout;
    private TransactionListAdapter adapter;
    private List<TransactionBean> data = new ArrayList<>();
    private int tradeType = TradeLineActivity.TRANSACTION_TYPE_ALL;
    private int page = 1;
    private TextView tvNoData;

    //所属链编号（默认值是4 TuborChain）
    private int chainId;
    //代币编号
    private String tokenId;


    public TransactionListFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.open_planet_fragment_transaction_list, container, false);
        initView(rootView);
        initData();
        return rootView;
    }


    private void initView(View rootView) {
        recyclerView = rootView.findViewById(R.id.recyclerView);
        tvNoData = rootView.findViewById(R.id.tv_no_data);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        refreshLayout = rootView.findViewById(R.id.refreshLayout);
        refreshLayout.setEnableAutoLoadMore(false);//开启自动加载功能（非必须）
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                page = 1;
                data.clear();
                adapter.notifyDataSetChanged();
                loadData(false);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                loadData(true);
            }
        });
    }

    private void initData() {
        if (getArguments() != null && getArguments().containsKey("type")) {
            tradeType = getArguments().getInt("type");
            chainId = getArguments().getInt("mode", IPAssetsConstant.CHAIN_ID_TURBOCHAIN);
            tokenId = getArguments().getString("tokenId");
        }

        adapter = new TransactionListAdapter(getContext(), R.layout.open_planet_item_transaction_list, data);
        recyclerView.setAdapter(adapter);
        refreshLayout.autoRefresh();

//        loadData(false);
    }

    //加载数据
    private void loadData(final boolean isLoadMore) {

//         chainId  所属链编号（默认值是4 TuborChain）
//         tokenId  代币编号，不是代币交易不需要传
//         page     第几页，默认值1
//         pagesize  每页记录数,默认值25
//         type     类型1全部2转出3转入4失败
//         walletAddress 钱包地址
        if (chainId == IPAssetsConstant.CHAIN_ID_BTC) {
            data.clear();
            final String address = getArguments().getString("address");
//            AccountDao accountDao = new AccountDao(getActivity());
//            Account account = accountDao.getAccount(address);
//            String filePath = account.getFileName();
//            BtcTransactionManager manager = BtcTransactionManager.getInstance(address, filePath);
            //fixme 以下注释代码为链上获取tx记录
//            List<TransactionBean> list = manager.getTransactions();
//            if (tradeType == TRANSACTION_TYPE_ALL) {
////                data.addAll(manager.getTransactions());
//            } else {
//                for (TransactionBean transactionBean : list) {
//                    if (tradeType == transactionBean.getTransactionType()) {
//                        data.add(transactionBean);
//                    }
//                }
//            }
            HashMap<String, String> params = new HashMap<>();
            params.put("type", BtcNetParamUtil.NET_TYPE);
            params.put("address", address);
            params.put("pagesize", "10");
            params.put("page", page + "");
            params.put("status", tradeType + "");
            JFCommonRequestManager.getInstance().requestGetByAsyn(TAG, BtcNetParamUtil.URL_BTC_TX_HISTORY,
                    params, new BaseRequestManager.ReqCodeCallBack<String>() {
                        @Override
                        public void onReqFailed(int errorCode, String errorMsg) {
                            ToastUtils.showShort(ResStringUtil.getString(R.string.common_text_http_request_data_fail));
                            finishRefresh(isLoadMore);
                        }

                        @Override
                        public void onReqSuccess(String result) {
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                if (jsonObject.optString("result").equals("success")) {
                                    //成功
                                    JSONArray jsonArray = jsonObject.optJSONArray("data");
                                    if (jsonArray.length() > 0) {
                                        for (int i = 0; i < jsonArray.length(); i++) {
                                            JSONObject txObject = jsonArray.optJSONObject(i);
                                            JSONArray inputArray = txObject.optJSONArray("inputs");

                                            StringBuilder fromAddress = new StringBuilder();
                                            for (int j = 0; j < inputArray.length(); j++) {
                                                JSONObject inputObject = inputArray.optJSONObject(j);
                                                JSONObject object = inputObject.optJSONObject("previousOutput");
                                                fromAddress.append(object.optString("address"))
                                                        .append("(").append(Coin.valueOf(object.optLong("value"))
                                                        .toFriendlyString()).append(")").append("\n");
                                            }
                                            JSONArray outputArray = txObject.optJSONArray("outputs");
                                            StringBuilder toAddress = new StringBuilder();
                                            for (int j = 0; j < outputArray.length(); j++) {
                                                JSONObject inputObject = outputArray.optJSONObject(j);
                                                toAddress.append(inputObject.optString("address"))
                                                        .append("(").append(Coin.valueOf(inputObject.optLong("value"))
                                                        .toFriendlyString()).append(")").append("\n");
                                            }
                                            TransactionBean transactionBean = new TransactionBean.Builder()
                                                    .transactionNumber(txObject.optString("txHash"))
                                                    .transactionStatus(true)
                                                    .transactionType(txObject.optInt("type")
                                                            == 3 ? TRANSACTION_TYPE_IN : TRANSACTION_TYPE_OUT)
                                                    .fromAddress(fromAddress.toString())
                                                    .toAddress(toAddress.toString())
                                                    .amount(Coin.valueOf(outputArray.optJSONObject(0).optLong("value")).toFriendlyString())
                                                    .gas(Coin.valueOf(txObject.optLong("fee")).toFriendlyString())
                                                    .time(TimeUtils.millis2String(txObject.optLong("time")*1000))
                                                    .chainId(chainId)
                                                    .block(String.valueOf(txObject.optInt("height")))
                                                    .build();
                                            data.add(transactionBean);
                                        }
                                    }
                                    adapter.notifyDataSetChanged();
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                //ToastUtils.showShort("请求失败，请重试");
                            }

                            if (data.size() == 0) {
                                tvNoData.setVisibility(View.VISIBLE);
                                tvNoData.setText(ResStringUtil.getString(R.string.common_text_no_data));
                            } else {
                                tvNoData.setVisibility(View.GONE);
                            }
                            finishRefresh(isLoadMore);
                        }

                        @Override
                        public void onReqFailed(String errorMsg) {

                        }
                    });

        } else if (chainId == EosNetParamUtil.getEosChainId()) {
            HashMap<String, String> map = new HashMap<>();
            map.put("account", getArguments().getString("address"));
//            map.put("account", "eosio");
            map.put("page", page + "");
            map.put("pagesize", "10");
            map.put("type", String.valueOf(tradeType));
            TCRequestUtil.getCommonRequest(TAG, "eos/getTxsDataByAccount", map,
                    new TCRequestUtil.TCRequestCallback() {
                @Override
                public void onSuccess(String response) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        if (jsonObject.optString("result").equals("success")) {
                            //成功
                            JSONArray jsonArray = jsonObject.optJSONObject("data").optJSONArray("data");
                            if (jsonArray.length() > 0) {
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    JSONObject txObject = jsonArray.optJSONObject(i);
                                    TransactionBean transactionBean = new TransactionBean.Builder()
                                            .transactionNumber(txObject.optString("trx_id"))
                                            .transactionStatus(true)
                                            .transactionType(txObject.optString("to")
                                                    .equals(getArguments().getString("address")) ?
                                                    TRANSACTION_TYPE_IN : TRANSACTION_TYPE_OUT)
                                            .fromAddress(txObject.optString("from"))
                                            .toAddress(txObject.optString("to"))
                                            .amount(txObject.optString("quantity"))
                                            .gas(txObject.optString(""))
                                            .note(txObject.optString("mome"))
                                            .time(txObject.optString("expiration"))
                                            .block(txObject.optString("account"))
                                            .chainId(chainId)
                                            .build();
                                    data.add(transactionBean);
                                }
                            }
                            adapter.notifyDataSetChanged();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        //ToastUtils.showShort("请求失败，请重试");
                    }

                    if (data.size() == 0) {
                        tvNoData.setVisibility(View.VISIBLE);
                        tvNoData.setText(ResStringUtil.getString(R.string.common_text_no_data));
                    } else {
                        tvNoData.setVisibility(View.GONE);
                    }
                    finishRefresh(isLoadMore);
                }

                @Override
                public void onFail(String error) {
                    ToastUtils.showShort(ResStringUtil.getString(R.string.common_text_http_request_data_fail));
                    finishRefresh(isLoadMore);
                }
            });
        }else {
            HashMap<String, String> map = new HashMap<>();
//        map.put("chainId", String.valueOf(IPAssetsConstant.CHAIN_ID_TURBOCHAIN));
            map.put("chainId", String.valueOf(chainId));
            if (tokenId != null) {
                map.put("tokenId", tokenId);
            }
//        map.put("tokenId",)
            map.put("page", page + "");
            map.put("pagesize", "10");
            map.put("type", String.valueOf(tradeType));
            map.put("walletAddress", getArguments().getString("address"));
            TCRequestUtil.getCommonRequest(TAG, "chain/txlist_accounts", map,
                    new TCRequestUtil.TCRequestCallback() {
                @Override
                public void onSuccess(String response) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        if (jsonObject.optString("result").equals("success")) {
                            //成功
                            JSONArray jsonArray = jsonObject.optJSONArray("txlist_accounts");
                            if (jsonArray != null && jsonArray.length() > 0) {
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    JSONObject txObject = jsonArray.optJSONObject(i);
                                    TransactionBean transactionBean = new TransactionBean.Builder()
                                            .transactionNumber(txObject.optString("txHash"))
                                            .transactionStatus(true)
                                            .transactionType(txObject.optString("status")
                                                    .equals("receiver") ? TRANSACTION_TYPE_IN : TRANSACTION_TYPE_OUT)
                                            .fromAddress(txObject.optString("from"))
                                            .toAddress(txObject.optString("to"))
                                            .amount(txObject.optString("value"))
                                            .gas(txObject.optString("txFee"))
                                            .time(txObject.optString("age"))
                                            .chainId(chainId)
                                            .block(String.valueOf(txObject.optInt("block")))
                                            .build();
                                    data.add(transactionBean);
                                }
                            }
                            adapter.notifyDataSetChanged();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        //ToastUtils.showShort("请求失败，请重试");
                    }

                    if (data.size() == 0) {
                        tvNoData.setVisibility(View.VISIBLE);
                        tvNoData.setText(ResStringUtil.getString(R.string.common_text_no_data));
                    } else {
                        tvNoData.setVisibility(View.GONE);
                    }
                    finishRefresh(isLoadMore);
                }

                @Override
                public void onFail(String error) {
                    ToastUtils.showShort(ResStringUtil.getString(R.string.common_text_http_request_data_fail));
                    finishRefresh(isLoadMore);
                }
            });
        }
    }

    //结束刷新
    private void finishRefresh(boolean isLoadMore) {
        if (isLoadMore) {
            refreshLayout.finishLoadMore(100);
        } else {
            refreshLayout.finishRefresh(100);
        }
    }

    public class TransactionListAdapter extends CommonAdapter<TransactionBean> {

        public TransactionListAdapter(Context context, int layoutId, List<TransactionBean> datas) {
            super(context, layoutId, datas);
        }

        @Override
        protected void convert(com.efounder.recycleviewhelper.base.ViewHolder holder, final TransactionBean transactionBean, int position) {
            ImageView mIvType;
            TextView mTvAddress;
            TextView mTvTime;
            TextView mTvAmount;

            mIvType = (ImageView) holder.getView(R.id.iv_type);
            mTvAddress = (TextView) holder.getView(R.id.tv_address);
            mTvTime = (TextView) holder.getView(R.id.tv_time);
            mTvAmount = (TextView) holder.getView(R.id.tv_amount);

            //转出
            if (transactionBean.getTransactionType() == TRANSACTION_TYPE_OUT) {
                mIvType.setImageDrawable(getResources().getDrawable(R.drawable.icon_txsend));
                if (chainId != IPAssetsConstant.CHAIN_ID_BTC) {
                    mTvAmount.setText("-" + transactionBean.getAmount());
                } else {
                    mTvAmount.setText(transactionBean.getAmount());
                }

                if (!transactionBean.getToAddress().equals("")) {
                    String formatTxNumber = "";
                    if (chainId == IPAssetsConstant.CHAIN_ID_BTC) {
                        formatTxNumber = transactionBean.getTransactionNumber().replace(transactionBean.getTransactionNumber()
                                .substring(6, transactionBean.getTransactionNumber().length() - 4), "****");
                    }else {
                        formatTxNumber = transactionBean.getToAddress().replace(transactionBean.getToAddress()
                                .substring(6, transactionBean.getToAddress().length() - 4), "****");
                    }
                    if (chainId == EosNetParamUtil.getEosChainId()) {
                        mTvAddress.setText(transactionBean.getToAddress());
                    }else {
                        mTvAddress.setText(formatTxNumber);
                    }

                }

            } else {
                mIvType.setImageDrawable(getResources().getDrawable(R.drawable.icon_txreceive));
                mTvAmount.setText("+" + transactionBean.getAmount());
                if (!transactionBean.getFromAddress().equals("")) {
                    String formatTxNumber = "";
                    if (chainId == IPAssetsConstant.CHAIN_ID_BTC) {
                        formatTxNumber = transactionBean.getTransactionNumber().replace(transactionBean.getTransactionNumber()
                                .substring(6, transactionBean.getTransactionNumber().length() - 4), "****");
                    }else {
                        formatTxNumber = transactionBean.getFromAddress().replace(transactionBean.getFromAddress()
                                .substring(6, transactionBean.getFromAddress().length() - 4), "****");
                    }

                    if (chainId == EosNetParamUtil.getEosChainId()) {
                        mTvAddress.setText(transactionBean.getFromAddress());
                    }else {
                        mTvAddress.setText(formatTxNumber);
                    }
                }
            }


            mTvTime.setText(transactionBean.getTime());

            holder.getConvertView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //交易详情
                    TransactionDetailActivity.start(getActivity(), transactionBean);
                }
            });
        }
    }
}
